package com.wxy.channel;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 使用异步io读取数据
 * @author 47868
 */

public class 异步IO {
    public static void main(String[] args) {
        try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(Paths.get("test1.txt"), StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(24);
            System.out.println(Thread.currentThread().getName() + ": read begin");
            /**
             * 参数
             * 1.ByteBuffer
             * 2.读取的起始位置
             * 3.附件 通常是 buffer 应对buffer空间不足场景
             * 4.回调对象 CompletionHandler
             */
            asyncChannel.read(buffer,0,buffer,new CompletionHandler<Integer, ByteBuffer>() {

                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println(Thread.currentThread().getName() + ": read completed " + result);
                    attachment.flip();
                    while (attachment.hasRemaining()) {
                        System.out.print((char) attachment.get());
                    }
                    attachment.clear();
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            System.out.println(Thread.currentThread().getName() + ": read end");
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
